#include "read.h"

constexpr unsigned int MAX_BUF = 4096;

ssize_t readData(int listener, void *data, size_t number)
{
    size_t count = number;

    ssize_t alreadyRead = 0;

    ssize_t readSum = 0;

    char * ptr = static_cast<char *>(data);

    while (0 < count) {

        alreadyRead = read(listener, ptr, count);

        if (0 > alreadyRead) {

            if (errno == EINTR) {
                alreadyRead = 0;
            } else if (errno == EAGAIN) {
                return readSum;
            } else {
                return -1;
            }
        }

        readSum += alreadyRead;

        count -= alreadyRead;

        ptr += alreadyRead;

    }

    return readSum;
}

ssize_t readData(int listener, std::string &buffer, bool &zero)
{
    ssize_t nread = 0;
    ssize_t readSum = 0;
    while (true)
    {
        char buff[MAX_BUF];
        if ((nread = read(listener, buff, MAX_BUF)) < 0)
        {
            if (errno == EINTR)
                continue;
            else if (errno == EAGAIN)
            {
                return readSum;
            }
            else
            {
                perror("read error");
                return -1;
            }
        }
        else if (nread == 0)
        {
            //printf("redsum = %d\n", readSum);
            zero = true;
            break;
        }
        //printf("before inBuffer.size() = %d\n", inBuffer.size());
        //printf("nread = %d\n", nread);
        readSum += nread;
        //buff += nread;
        buffer += std::string(buff, buff + nread);
        //printf("after inBuffer.size() = %d\n", inBuffer.size());
    }
    return readSum;
}
